<?php

class TPersonaController extends AweController {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';
    public $defaultAction = 'admin';
    public $admin = true;

    public function filters() {
        return array(
            array('CrugeAccessControlFilter'),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id, $tipo = null) {
        if (!$tipo) {
            $tipo = "perfil";
        }
        $this->render('view', array(
            'model' => $this->loadModel($id), 'tipo' => $tipo
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new TPersona;


        if (isset($_POST['TPersona'])) {
            $model->attributes = $_POST['TPersona'];
            if ($model->per_foto != null && $model->per_cedula != null) {

                if (!file_exists('uploads/personas/' . $model->per_cedula)) {
                    mkdir('uploads/personas/' . $model->per_cedula, 0777, true);
                }
                $path = realpath(Yii::app()->getBasePath() . "/../uploads/personas/$model->per_cedula") . "/";
                $pathorigen = realpath(Yii::app()->getBasePath() . "/../uploads/tmp/") . "/";
                $publicPath = Yii::app()->getBaseUrl() . "/uploads/personas/$model->per_cedula" . '/';
                if (rename($pathorigen . $model->per_foto, $path . $model->per_foto)) {
                    $model->per_foto = $publicPath . $model->per_foto;
                }
            }
            $save_model = $model->save();
            if ($save_model) {

                $this->redirect(array('admin'));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);


        if (isset($_POST['TPersona'])) {
            $model->attributes = $_POST['TPersona'];
            $model->attributes = $_POST['TPersona'];
            if ($model->per_foto != null && $model->per_cedula != null) {

                if (!file_exists('uploads/personas/' . $model->per_cedula)) {
                    mkdir('uploads/personas/' . $model->per_cedula, 0777, true);
                }
                $path = realpath(Yii::app()->getBasePath() . "/../uploads/personas/$model->per_cedula") . "/";
                $pathorigen = realpath(Yii::app()->getBasePath() . "/../uploads/tmp/") . "/";
                $publicPath = Yii::app()->getBaseUrl() . "/uploads/personas/$model->per_cedula" . '/';
                if (rename($pathorigen . $model->per_foto, $path . $model->per_foto)) {
                    $model->per_foto = $publicPath . $model->per_foto;
                }
            }
            $save_model = $model->save();
            if ($save_model) {

                $this->redirect(array('admin'));
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new TPersona('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['TPersona']))
            $model->attributes = $_GET['TPersona'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id, $modelClass = __CLASS__) {
        $model = TPersona::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model, $form = null) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'tpersona-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionAjaxUploadTemp() {
        if (Yii::app()->request->isAjaxRequest) {
            //nombre de la carpeta
            $carpeta = 'tmp';
            $path = realpath(Yii::app()->getBasePath() . "/../uploads/" . $carpeta . "/") . "\\";
            $publicPath = Yii::app()->getBaseUrl() . "/uploads/" . $carpeta . "/";
//            var_dump("pat", $publicPath);
//            die();
            if (isset($_GET['_method'])) {
//                var_dump($_GET);
                if ($_GET['_method'] == 'delete') {
                    $file = $path . $_GET["file"];
                    if (is_file($file)) {
                        // borrar el archivo del path correspondiente
                        unlink($file);
                        echo CJSON::encode(array("success" => true));
                    } else {
                        echo CJSON::encode(array("success" => false));
                    }
                }
                Yii::app()->end();
            }


            //obtenemos el archivo a subir
            $file = $_FILES['file'];
            //comprobamos si existe un directorio para subir el archivo
            //si no es así, lo creamos
            if (!file_exists('uploads/')) {
                var_dump("paso");
                if (mkdir('uploads/', 0777, true)) {
//                    var_dump("creacion");

                    chmod("uploads/", 0777);
                    chdir(getcwd() . '/uploads/');
                    if (!file_exists($carpeta . '/')) {
                        mkdir($carpeta . '/', 0777, true);
                        chmod("$carpeta/", 0777);
                    }
                }
            }
//            die();
            // creacion de los path para el guardado de los multiples archivos con el $id y $carpeta correspondiente
            $filename = time('U') . rand(0, time('U')) . '.' . Util::getExtensionName($file['name']);
            //comprobamos si el archivo ha subido
            if ($file && move_uploaded_file($_FILES['file']['tmp_name'], $path . $filename)) {
                echo CJSON::encode(array(
                    "success" => true,
                    "data" => array(
                        'name' => $filename,
                        'size' => $file['size'],
                        'url' => $path . $filename,
                        'src' => $publicPath . $filename,
                        'delete_url' => $this->createUrl('ajaxUploadTemp', array(
                            '_method' => "delete",
                            'file' => $filename,
                            "carpeta" => $carpeta
                        ))
                )));
            }
        } else {
            echo CJSON::encode(array("success" => false));
        }
    }

}
